/**
 * 
 */
package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.Controller.ThreadReceiveFile;
import com.application.Controller.ThreadSendFile;

public class FrmChatPeer extends Activity implements OnClickListener,OnKeyListener {
	private static final int SENDFILE = Menu.FIRST+7;
	EditText _edtmessage;
	static private ArrayList<String> _messages = new ArrayList<String>();
	static MyChatPeerAdapter _myAdapter;
	Button _btnSend;
	static ListView _lvcontentchat;
	static String _IPFriend;
	String _fullNameFriend;
	static String _userNameFriend;
	private static String _pathContentChat; 
	static Context _cont;
	private TextView _txtusername;
	private TextView _txtfullname;
	String _textSend = "";
	static protected Runnable _runUpdateMsg;
	static Handler _handler = new Handler();
	String _acc = "";
	String _mess = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.frm_chatpeer);

		_cont = this;
		_edtmessage = (EditText) findViewById(R.id.chatpeer_txtmessage);
		_btnSend = (Button) findViewById(R.id.chatpeer_btnSend);
		_txtusername = (TextView) findViewById(R.id.chatpeer_txtusername);
		_txtfullname = (TextView) findViewById(R.id.chatpeer_txtfullname);
		_lvcontentchat = (ListView) findViewById(R.id.chatpeer_lvcontent);
		_lvcontentchat.setDividerHeight(0);

		NetworkController.init_runnableUpdateMsg();

		// lay DC IP duoc goi qua tu form Profile
		_userNameFriend = getIntent().getExtras().getString("username");
		_fullNameFriend = getIntent().getExtras().getString("fullname");
		_IPFriend = getIntent().getExtras().getString("IP");

		_txtfullname.setText(_fullNameFriend);
		_txtusername.setText(_userNameFriend);

		_pathContentChat = ReadWriteFileController.DIRECTORYCHATPEER + "Peer_"+ _userNameFriend + "_Content.txt";
		// ---------xac dinh editext enter khi chat------------------
		_edtmessage.setOnKeyListener(this);
		setListAdapter();
		// thiết lập sự kiện nhấn nút Send và bấm ENTER
		_btnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sendMessage();
			}
		});
	}

	public static void setPathContentChat(String userName)
	{
		_pathContentChat = ReadWriteFileController.DIRECTORYCHATPEER + "Peer_"+ userName + "_Content.txt";
	}
	
	public static void setListAdapter() {
		_messages.clear();
		_messages = ReadWriteFileController.ReadTXT(_pathContentChat);
		_myAdapter = new MyChatPeerAdapter(_cont, R.layout.row_chatpeer,_messages);
		_lvcontentchat.setAdapter(_myAdapter);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//ReadWriteFileController.deleteFile(_pathContentChat);

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("PEERDROID","vao onstart chat peer");
		ActivityController.setPeerActivity(this);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//		ShowSubjectList();	
		Log.d("PEERDROID", "vao resume");
		ActivityController.setPeerActivity(this);
	}
	/**
	 * ham set lai noi dung message chat tren list
	 * 
	 * @param acc
	 * @param mess
	 */
	public static void updateMessage(String userName, String ip) {
		_userNameFriend = userName;
		_IPFriend = ip;
		_messages = new ArrayList<String>();
		setListAdapter();
		// _handler.post(_runUpdateMsg);
	}

	public static void updateMessage() {
		_messages = new ArrayList<String>();
		setListAdapter();
	}
	/**
	 * khi xoay man hinh thi noi dung tren list khong bien mat
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	/**
	 * goi khi send messge di, click send
	 * 
	 * @throws IOException
	 */
	private void sendMessage() {
		String text = _edtmessage.getText().toString();
		String textSend = NetworkController.get_userName() + "/" + NetworkController.get_fullName() + "/" + text;
		// set lai message show len list
		if (!text.equals("")) {
			// --------ghi noi dung chat xuong-------------
			try {
				ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATPEER +"Peer_"+ _userNameFriend + "_Content.txt", "Tôi: " + text);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			setListAdapter();

			//cập nhật lại conversation
			Log.d("PEERDROID","keychat: " + _userNameFriend + " text: " + text + "type: " + 1 + "IP: " + _IPFriend + "fullName: " +_fullNameFriend );
			NetworkController.UpdateMessageInConversation(_userNameFriend, text, 1, _IPFriend, _fullNameFriend);


			// thuc hien gui thong diep den ban chat
			NetworkController.SendChatMessagePeer(new Address(_IPFriend), textSend);
			_edtmessage.setText("");
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_ENTER:
			sendMessage();
			return true;
		}
		return false;
	}

	private static class MyChatPeerAdapter extends ArrayAdapter<String> {
		private Context _context;
		// private LayoutInflater mInflater;
		private int _resource;
		private Resources mResources;
		private ArrayList<String> mMessages;

		public MyChatPeerAdapter(Context context, int resource,
				ArrayList<String> arrmess) {
			// mInflater = LayoutInflater.from(context);
			// mResources = context.getResources();
			super(context, resource, arrmess);
			_context = context;
			_resource = resource;
			mMessages = arrmess;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mMessages.size();
		}

		@Override
		public long getItemId(int pos) {
			// TODO Auto-generated method stub
			return pos;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final String messView = mMessages.get(position);
			if (convertView == null) {
				LayoutInflater lInflater = (LayoutInflater) this.getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = lInflater.inflate(R.layout.row_chatpeer, null,
						true);
			}
			if (messView != null) {
				TextView txtContent = (TextView) convertView.findViewById(R.id.row_txtcontent);
				LinearLayout llo = (LinearLayout) convertView.findViewById(R.id.row_lloreceivefile);
				TextView txtFileName = (TextView)convertView.findViewById(R.id.row_txtfilename);
				TextView txtOk = (TextView)convertView.findViewById(R.id.row_txtok);
				TextView txtCancel = (TextView)convertView.findViewById(R.id.row_txtcancel);

				String[] sTemp = messView.split(":");
				String mess = getMessage(sTemp);
				String firsttext=sTemp[0];
				//-----------------co file goi den------------
				if(firsttext.equals("##file##")){
					txtContent.setVisibility(View.GONE);
					llo.setVisibility(View.VISIBLE);
					txtCancel.setVisibility(View.VISIBLE);
					txtFileName.setVisibility(View.VISIBLE);
					txtOk.setVisibility(View.VISIBLE);
					//nhan duoc tap tin dinh kem
					String[] content = mess.split("##");
					final String t = content[2];
					final String address = content[3];
					final String port = content[4];
					txtFileName.setText(content[0] + content[1] + content[2]);

					//set su kien khi dong y nhan file
					txtOk.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							Toast toast = Toast.makeText(ActivityController.getPeerActivity(),"Ok", Toast.LENGTH_SHORT);
							toast.show();
							Intent intent = new Intent(ActivityController.getPeerActivity().getBaseContext(), FrmSelectFile.class);
							FrmSelectFile.setFileName(t);
							FrmSelectFile.set_address(address);
							FrmSelectFile.set_port(port);
							FrmSelectFile.set_lineToRemove(messView);
							ActivityController.getPeerActivity().startActivityForResult(intent, 1);
						}
					});
					//set su kien khi khong dong y nhan file
					txtCancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							Toast toast = Toast.makeText(ActivityController.getPeerActivity(),"Cancel", Toast.LENGTH_SHORT);
							toast.show();
							
						}
					});
				}
				//-----------co thong bao-------------
				else if(firsttext.equals("##notify##")){
					txtContent.setVisibility(View.VISIBLE);
					llo.setVisibility(View.GONE);
					txtCancel.setVisibility(View.GONE);
					txtFileName.setVisibility(View.GONE);
					txtOk.setVisibility(View.GONE);
					txtContent.setText(mess);
				}
				//-------------tin nhan chat---------------
				else{
					txtContent.setVisibility(View.VISIBLE);
					llo.setVisibility(View.GONE);
					txtCancel.setVisibility(View.GONE);
					txtFileName.setVisibility(View.GONE);
					txtOk.setVisibility(View.GONE);
					String fullName = sTemp[0];

					if (fullName.equals("Tôi")) {
						//txtUserName.setTextColor(Color.GRAY);
						txtContent.setText(Html.fromHtml("<b><font color='#696969' size='14'>" + fullName +": " +"</font></b>" + 
								"<font color='black' size='20'>" + mess + "</font>" ));
					}else{
						//txtUserName.setTextColor(Color.BLUE);
						txtContent.setText(Html.fromHtml("<b><font color='blue' size='14'>" + fullName +": " +"</font></b>" + 
								"<font color='black' size='20'>" + mess + "</font>" ));
					}
				}
			}

			return convertView;
		}

		private String getMessage(String[] temp) {
			String result = "";
			// i chay tu 2 đe lay ra message
			for (int i = 1; i < temp.length; i++) {
				if (i == temp.length - 1) {
					result = result + temp[i];
				} else {
					result = result + temp[i] + ":";
				}
			}
			return result;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, SENDFILE, Menu.NONE, "Gửi dữ liệu")
		.setIcon(R.drawable.attach_icon)
		.setAlphabeticShortcut('h');
		return(super.onCreateOptionsMenu(menu));
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case SENDFILE:
			Intent intent = new Intent(this,FrmSelectFile.class);
			intent.putExtra(FrmSelectFile.START_PATH, "/sdcard");
			this.startActivityForResult(intent, 1);
			//			startActivity(new Intent(this, FrmSelectFile.class));
			return(true);
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public synchronized void onActivityResult(final int requestCode,
			int resultCode, final Intent data) {
		Log.d("PEERDROID","onActivityResult" );
		if (resultCode == Activity.RESULT_OK) {

			String filePath = data.getStringExtra(FrmSelectFile.RESULT_PATH);
			String type = data.getStringExtra(FrmSelectFile.RESULT_TYPE);
			String address = data.getStringExtra(FrmSelectFile.RESULT_ADDRESS);
			String port = data.getStringExtra(FrmSelectFile.RESULT_PORT);
			String lineToRemove = data.getStringExtra(FrmSelectFile.RESULT_LINETOREMOVE);
			Log.d("PEERDROID","filepath: "+filePath );
			if(type.equals("1"))//luu file
			{
				Log.d("PEERDROID","save file");
				ThreadReceiveFile thread = new ThreadReceiveFile();
				thread.setPathChatFile(ReadWriteFileController.DIRECTORYCHATPEER +"Peer_"+ _userNameFriend + "_Content.txt");
				String[] temp = filePath.split("/");
				thread.setfName(temp[temp.length - 1]);
				thread.SetReceive(filePath, address, Integer.valueOf(port));
				thread.setLineToRemove(lineToRemove);
				thread.start();
			}
			else if(type.equals("2"))//send file
			{
				Log.d("PEERDROID","send file");
				ArrayList<Address>arrDSGourp = new ArrayList<Address>();
				arrDSGourp.add(new Address(_IPFriend));
				ThreadSendFile thread = new ThreadSendFile();
				thread.setSendFile(filePath, NetworkController.get_userName(), NetworkController.PORT_NUMBER_CURRENT++, "canhan", arrDSGourp);
				thread.start();
			}

		} else if (resultCode == Activity.RESULT_CANCELED) {
			Log.d("PEERDROID","file not selected" );
		}

	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		sendMessage();
	}

}
